import React, { useState } from 'react';
import { message } from 'antd';
import cn from 'classnames';
import styles from './form.less';
import { FormContainer } from './FormContainer';
import FormItem from './FormItem';

const FormBlock = props => {
    const {
        form,
        titleText = '请传入标题',
        addButtonText = '+请传入添加按钮名称',
        parentFieldData = [],
        parentField = '',
        formInfoList = {},
        id,
        required = false,
        disabled = false,
        hideBlock = false,
        children
    } = props;
    const [dataItemKeys, setDataItemKeys] = useState([0]);
    const initialKeysArr = parentFieldData.map((_, index) => index);
    const addFormList = () => {
        const validLength = (() => {
            let result = 0;
            if (dataItemKeys.length > 0) {
                dataItemKeys.forEach(key => {
                    if (!parentFieldData[key] || (parentFieldData[key] && parentFieldData[key].deleteFlag !== 1)) {
                        result += 1;
                    }
                });
            }
            return result;
        })();
        if (validLength < 10) {
            const newWorkKeys = [...dataItemKeys, dataItemKeys[dataItemKeys.length - 1] + 1];
            setDataItemKeys(newWorkKeys);
        } else {
            message.error('至多添加10个');
        }
    };
    const deleteGroup = targetKey => {
        if (parentFieldData[targetKey] && parentFieldData[targetKey].id) {
            parentFieldData[targetKey].deleteFlag = 1;
            form.setFieldsValue({
                [`${parentField}_deleteFlag_${targetKey}`]: 1
            });
            setDataItemKeys([...dataItemKeys]); // 为了更新页面
        } else {
            let newKeys = [];
            newKeys = dataItemKeys.filter(key => key !== targetKey);
            setDataItemKeys([...newKeys]);
        }
    };

    const getItemInitialValue = (key, list) => {
        if (parentFieldData[key]) {
            if (list.prop === 'dateRange') {
                return [parentFieldData[key].startTime, parentFieldData[key].endTime];
            }
            if (list.type === 'telephone') {
                return [parentFieldData[key].areaCode, parentFieldData[key][list.prop[1]]];
            }
            return parentFieldData[key][list.prop];
        }
        return [];
    };

    const renderFormItem = () => {
        if (parentFieldData.length > 0) {
            parentFieldData.forEach((item, key) => {
                if (item.id) {
                    form.getFieldDecorator(`${parentField}_id_${key}`, {
                        initialValue: item.id
                    });
                    form.getFieldDecorator(`${parentField}_deleteFlag_${key}`, {
                        initialValue: item.deleteFlag
                    });
                }
            });
        }
        const renderKeys = dataItemKeys.filter(key => {
            if (parentFieldData[key]) {
                return parentFieldData[key].deleteFlag !== 1;
            }
            return true;
        });
        return renderKeys.map(key => (
            <div className={styles.block} key={`parentFieldData${key}`}>
                {key !== 0 && !disabled ? (
                    <i
                        className={cn(styles.del, 'iconfont icongms_list_icon_fail_default')}
                        onClick={() => {
                            deleteGroup(key);
                        }}
                    />
                ) : (
                    ''
                )}
                <FormContainer>
                    {formInfoList.map(list => {
                        let newProp = `${parentField}_${list.prop}_${key}`;
                        if (Array.isArray(list.prop)) {
                            newProp = [
                                `${parentField}_${list.prop[0]}_${key}`,
                                `${parentField}_${list.prop[1]}_${key}`
                            ];
                        }
                        return (
                            <FormItem
                                {...list}
                                required={required}
                                initialValue={getItemInitialValue(key, list)}
                                key={`${parentField}_${list.prop}_${key}`}
                                prop={newProp}
                                {...props}
                            />
                        );
                    })}
                </FormContainer>
            </div>
        ));
    };
    React.useEffect(() => {
        if (initialKeysArr.length > 0) {
            setDataItemKeys(initialKeysArr);
        }
    }, [parentFieldData]);
    return (
        <>
            <div id={id || ''} className={styles.title}>
                {titleText}
            </div>
            {children}
            {/* 修复禁用状态下渲染空数据块的问题：临时解决方案：在禁用的状态下如果dataItemKeys是更新之前的数据则不渲染 */}
            {!hideBlock &&
                (parentFieldData.length === 0 ||
                    !disabled ||
                    (parentFieldData.length > 0 && dataItemKeys.length <= parentFieldData.length)) &&
                renderFormItem()}
            {!disabled && (
                <div
                    className={styles.add}
                    onClick={() => {
                        addFormList();
                    }}
                >
                    {addButtonText}
                </div>
            )}
        </>
    );
};

export default React.memo(FormBlock);
